package my2Cents.properties;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;

import javax.swing.JSlider;
import javax.swing.border.TitledBorder;

public class Slider extends Property {
	private static final long serialVersionUID = 1L;
	private JSlider slider;
	
	public Slider(String label, int value, int minValue, int maxValue, int tickSpacing, boolean anysnap) {
		slider = makeJSlider(label, value, minValue, maxValue, tickSpacing, anysnap);
		add(slider);
		centerY(slider);
	}
	
	public void validate() {
		super.validate();
		if(getParent() != null) {
			int w = getParent().getWidth();
			this.setSize(w,60);
			slider.setLocation(3,3);
			slider.setSize(getWidth()-6,getHeight()-6);
			slider.setPreferredSize(slider.getSize());
		}
	}
	
	public void setCloseKeyAdapter(KeyAdapter ka) {
		super.setCloseKeyAdapter(ka);
		slider.addKeyListener(getCloseKeyAdapter());
	}
	
	private JSlider makeJSlider(final String label, int value, int minValue, int maxValue, int tickSpacing, boolean anysnap) {
		final JSlider jSlider = new JSlider();
		final TitledBorder x = new TitledBorder(jSlider.getBorder()) {
			private static final long serialVersionUID = 1L;
			public void paintBorder(Component x, Graphics g, int cx, int cy, int w, int h) {
				Font f = new Font("Verdana",Font.BOLD,10);
				g.setFont(f);
				g.drawString(this.title,10,10);
			}
		};
		x.setTitle("" + label + " [" + value + "]");
		jSlider.setForeground(new Color(0,0,0));
		jSlider.setBackground(bgColor);
		jSlider.setMinimum(minValue);
		jSlider.setMaximum(maxValue);
		jSlider.setPaintTicks(true);
		jSlider.setValue(value);
		jSlider.setSnapToTicks(!anysnap);
		jSlider.setMinorTickSpacing((int) (tickSpacing/2));
		jSlider.setMajorTickSpacing(tickSpacing);
		jSlider.setBorder(x);
		jSlider.setPaintLabels(true);
		jSlider.addChangeListener(new javax.swing.event.ChangeListener() {
			@SuppressWarnings("unchecked")
			public void stateChanged(javax.swing.event.ChangeEvent e) {
				x.setTitle("" + label + " [" + jSlider.getValue() + "]");
				jSlider.setBorder(x);
				jSlider.paint(jSlider.getGraphics());
				valueChanged(jSlider.getValue());
			}
		});
		return jSlider;
	}
	
	public void valueChanged(int value) {
		
	}

}
